import { defineStore } from 'pinia'
import request from '@/extensions/axios'
import Cookies from 'js-cookie'
const env = import.meta.env
export const useUserStore = defineStore('user', {
  state:  () => {
    return {
      user:null,
      lifetime:null,
      loading:false,
      error:null,
      loaded:false,
    }
  },
  getters: {
    isLoggedIn: (state) => {
      return state?.user?.id;
    },
    isAdmin: (state) => {
      return state?.user?.admin?.id;
    }
  },
  actions: {
    async fetchUser(force=false) {
      if(!force && this.loaded){
        return
      }
      if(this.loading){
        return;
      }
      this.loading = true;
      const response = await request.get('/open/user')
      this.loading = false;
      if(response.status === 200 &&
          response.data &&
          typeof response.data.user!="undefined"
      ){
        this.user = response.data.user;
        this.lifetime = response.data.lifetime;
        this.loaded = true;
      }
    },
    async logout() {
      if(env.VITE_WEB_API_MODEL!='api'){
        let is_wechat = navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger";
        let response;
        try{
            response = await request.post('/open/logout',{
                is_wechat:is_wechat
            })
        }catch(error){
          response = error.response;
        }
        if(response.status !== 302){
          return false;
        }
      }
      Cookies.remove('Authorization')
      this.user = null;
      this.lifetime = null;
    },
    setUser(user){
      this.user = user;
    },
    setLifetime(lifetime){
      this.lifetime = lifetime;
    },
    //登录成功
    async loginSuccess(data,$router){
      let redirect_url = data.redirect_url;
      if(redirect_url && redirect_url!='/open/login'){
          if(data.lifetime){
              this.setLifetime(data.lifetime);
          }
          if(data.token){
            Cookies.set('Authorization', data.token);
            if(data.user){
              this.setUser(data.user);
            }else{
              await this.fetchUser(true);
            }
          }
          $router.replace('/home');
        }else{
          $router.push('/guest/login/password');
        }
    }
  }
})